import { delay } from "@/utils";
import { ref } from "vue";

export const useTextPrintContent = (options) => {
  const { singlePrintCallback } = options || {};
  let complete = null;

  const showContent = ref("");
  const needPrintContentList = ref([]);
  let endFlag = ref(false);

  let takeTextFlag = ref(false);
  const takeText = async () => {
    if (takeTextFlag.value) return;
    takeTextFlag.value = true;
    while (
      needPrintContentList.value.length ||
      (!endFlag.value && needPrintContentList.value.length)
    ) {
      await delay(50);
      const shiftText = needPrintContentList.value.shift();
      if (!shiftText) continue;
      showContent.value += shiftText;
      singlePrintCallback && singlePrintCallback();
    }
    takeTextFlag.value = false;
    complete && complete();
  };

  const pushContent = (content) => {
    needPrintContentList.value.push(...content.split(""));
    if (!endFlag.value) {
      takeText()
    }
  };

  const setStart = () => {
    showContent.value = "";
    needPrintContentList.value = [];
    endFlag.value = false;
    complete = null
  };

  const setEnd = (callback) => {
    endFlag.value = true;
    complete = callback;
  };

  return {
    showContent,
    pushContent,
    setStart,
    setEnd,
  };
};
